package com.lihepeng.leecode.slip_window;


import org.junit.Test;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 滑动窗口
 * 给定一个字符串 s ，请你找出其中不含有重复字符的 最长子串 的长度。
 */
public class Solution3 {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() ==0) {
            return 0;
        }
        Set<Character> paramSet = new HashSet<>();
        int left =0,right=0;
        int ans =0;
        while (right <s.length()) {
            char c = s.charAt(right);
            paramSet.add(c);
            right++;
            // 收缩
            while (paramSet.contains(s.charAt(left))) {

                paramSet.remove(s.charAt(left));
                left ++;
                ans = Math.min(ans,right-left);
            }
        }
        return ans;

    }

    public int lengthOfLongestSubstring1(String s) {
        if (s == null || s.length() ==0) {
            return 0;
        }
        Map<Character,Integer> map = new HashMap<>();
        int left =0,right=0,ans =0;
        while (right <s.length()) {
            char x = s.charAt(right);

            if (map.containsKey(x)) {
                left = Math.max(left,map.get(x));
            }
            ans = Math.max(right-left+1,ans);
            map.put(s.charAt(right) ,right+1);
            right++;
        }
        return ans;

    }
    @Test
    public void runTest(){
        int abcdbc = this.lengthOfLongestSubstring1("abcdbc");
        System.out.println(abcdbc);
    }
}
